package com.mykt.gateway.filter;


import com.mykt.constant.SecurityConstants;
import com.mykt.constant.TokenConstants;
import com.mykt.gateway.config.properties.IgnoreWhiteProperties;
import com.mykt.gateway.exception.MyWebException;
import com.mykt.service.RedisService;
import com.mykt.utils.servlet.ServletUtils;
import com.mykt.utils.StringUtils;
import com.mykt.utils.token.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {


    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //127.0.0.1:9999/mykt-system/mykt/system/user/info?userName=admin

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();

        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        //获取接口请求中的token
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return MyWebException.exception(exchange,"token不能为空");
        }

        //获取token是否存在 并 解析token信息
        Map<String,String> tokenInfo= this.tokenInfo(token);
        if(tokenInfo == null){
            return MyWebException.exception(exchange,"token已过期");
        }

        String userId = tokenInfo.get("userId");
        String userName = tokenInfo.get("userName");
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName)) {
            return MyWebException.exception(exchange,"token解析失败");
        }

        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userId);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, userName);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }


    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }


    /**
     * 获取接口请求中的token 并拼接
     * @param request
     * @return
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    /**
     * 解析token，并获取到用户信息
     * @param token
     * @return
     */
    private Map<String,String> tokenInfo(String token){
        String redisTokenKey=getTokenKey(token);

        Object cacheObject = redisService.getCacheObject(redisTokenKey);
        if(cacheObject == null){
            return null;
        }
        return TokenUtils.getUserInfo(token);
    }



    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    /**
     * 获取存在reids中的tokenKey
     * @param token
     * @return
     */
    private String getTokenKey(String token)
    {
        return TokenConstants.TOKEN_KEY_PREFIX + token;
    }

    @Override
    public int getOrder() {
        return -1;
    }



}
